// pages/goods/goods-detail/goods-detail.js
//调用方式/pages/goods/goods-detail/goods-detail?goodId=1321&skuId=1554"
//购物车调用需实现onResultCartGoodCountAdd(goodId, skuId, count)方法

import * as echarts from '../../../ec-canvas/echarts';
var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var emptyUtil = require('../../templates/empty/empty.js')
const app = getApp()
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    identity:null,

    show:false,
    emptyParam: {
      emptyStatus: 0
    },
    goodDetail: "", //商品详情信息
    cartCount: 0, //购物车数量
    isSwiperVideoPlaying: false, //是否正在播放

    priceEc: {
      lazyLoad: true // 将 lazyLoad 设为 true 后，需要手动初始化图表
    },
    isInitEc: false, //是否已初始化ECharts

    inputBuyCount: 0, //购买数量
    maxLimitBuyCount: 0, //最大可购买数量

    //商品确认弹出框内容
    showConfirmDialog: false, //是否显示
    confirmDialogType: 1, //1:加入购物车 2：立即购买
    isAndroid: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    that = this;
    var goodId = options.goodId
    var skuId = options.skuId
    if (!goodId || !skuId) { //未设置-退出
      wx.navigateBack({})
      return;
    }
    uiUtil.showLoading("正在加载中..")
    //获取详情
    this.requestGoodsDetail(goodId, skuId)
    //正在进行中的购物车数量
    this.requestGoingOrderCount()
    that.setData({
      identity:app.globalData.identity
    })

  },
  onReady: function() {
    // 获取组件
    this.priceChatDom = this.selectComponent('#price-chart-dom');
    that.initPriceChart()
  },
  onShareAppMessage: function(res) {
    return util.handleShareApp('goods-detail',that.data.goodDetail)
  },

  /**
   * 获取商品详情
   */
  requestGoodsDetail(goodId, skuId) {
    httpUtil.PostRequest("good_detail", {
      goodId: goodId,
      skuId: skuId,
    }, {
      complete() {
        wx.hideLoading()
      },
      success(res) {
        try {
          var length = res.goodImageList.length
          for (var i = 0; i < length; i++) {
            var item = res.goodImageList[i]
            res.goodImageList[i] = item.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
          }
        } catch (e) {
          console.log(e)
        }

        var maxCount = res.maxBuyCount || 0
        if (res.stockCount && maxCount > res.stockCount) {
          maxCount = res.stockCount
        }

        that.setData({
          goodDetail: res,
          maxLimitBuyCount: maxCount
        })
        that.initInputBuyCount()
        that.initPriceChart()
      },
      fail(code, res) {
        var text = res || "获取商品信息失败"
        emptyUtil.showFailView(text)
      }
    })
  },
  /**
   * 初始化购买数量
   */
  initInputBuyCount() {
    try {
      var goodDetail = this.data.goodDetail
      var buyCount = goodDetail.minBuyCount || 0;
      if (buyCount > goodDetail.stockCount) { //大于库存数量
        buyCount = goodDetail.stockCount
      }
      this.setData({
        inputBuyCount: buyCount
      })
    } catch (e) {}
  },
  /**
   * 获取正在进行中的订单数据
   */
  requestGoingOrderCount() {
    httpUtil.PostRequest("going_order_count", {}, {
      success(res) {
        //更新全局变量
        if (res.cardCount) {
          that.setData({
            cartCount: res.cardCount
          })
          app.resetCartCount(res.cardCount)
        }
      },
      fail(code, res) {},
      complete() {}
    })
  },

  /**
   *点击轮播图片放大预览
   */
  onSwiperImageTap(e) {
    that = this;
    var url = e.target.dataset.url;
    var urls = [];
    var img = this.data.goodDetail.swiperList;
    for (var a = 0; a < img.length; a++) {
      if (img[a].type == "image") {
        urls.push(img[a].imageUrl);
      }
    }
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  /**
   * 轮播图视频开始播放
   */
  onSwiperVideoPlay(e) {
    this.setData({
      isSwiperVideoPlaying: true
    })
  },
  /**
   * 轮播图视频暂停播放
   */
  onSwiperVideoPause(e) {
    this.setData({
      isSwiperVideoPlaying: false
    })
  },
  /**
   * 初始化图标
   */
  initPriceChart() {
    if (this.data.isInitEc || !this.priceChatDom || !this.data.goodDetail) {
      return;
    }
    this.setData({
      isInitEc: true,
    })

    var priceList = this.data.goodDetail.priceList
    // if (!priceList || priceList.length == 0) {
    //   return
    // }
    this.priceChatDom.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      //整理横坐标，value值

      var xDatas = []
      var yValues = []
      var length = priceList.length
      for (var i = 0; i < length; i++) {
        var item = priceList[i]
        xDatas.push(item.date)
        yValues.push(item.price)
      }
      setChartOption(chart, xDatas, yValues);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  /**
   * 购买数量-减少
   */
  onBugCountCutClick() {
    var lastCount = this.data.inputBuyCount || 0;
    if (lastCount == 0) { //原数量为0
      return;
    } else {
      var count = lastCount - 1
      this.setData({
        inputBuyCount: count
      })
    }
  },

  /**
   * 购买数量-增加
   */
  onBugCountAddClick() {
    var lastCount = this.data.inputBuyCount || 0;
    var count = lastCount + 1
    if (count > this.data.goodDetail.maxBuyCount) {
      uiUtil.showToast("已超出最大购买数量")
      return;
    } else if (count > this.data.goodDetail.stockCount) {
      uiUtil.showToast("已超出库存数量")
      return;
    }
    this.setData({
      inputBuyCount: count
    })
  },

  onGoCartBtnClick() {
    wx.navigateTo({
      url: '../../cart/cart'
    })
  },

  /**
   * 联系客服点击
   */
  contactBtnClick() {
    var phoneNo = this.data.goodDetail.hotlineNo
    if (phoneNo) {
      wx.makePhoneCall({
        phoneNumber: phoneNo,
      })
    }
  },

  /**
   * 更多价格分析跳转
   */
  onMorePriceChartClick() {
    var strDetail = JSON.stringify(this.data.goodDetail)
    wx.navigateTo({
      url: '/pages/goods/price-chart/price-chart?goodDetail=' + encodeURIComponent(strDetail),
    })
  },
  onBuyClick() {
    if (this.data.maxLimitBuyCount == 0) {
      uiUtil.showToast("抱歉,商品已售罄")
      return;
    }
    this.setData({
      confirmDialogType: 2
    })
    that.showConfirmDialog()
  },

  /**
   * 立即购买点击
   */
  onBuyClickConfirm() {
    if (this.data.maxLimitBuyCount == 0) {
      uiUtil.showToast("抱歉,商品已售罄")
      return;
    }
    var buyCount = this.data.inputBuyCount
    if (buyCount <= 0) {
      uiUtil.showToast("请选择购买数量")
      return;
    }
    this.hideConfirmDialog()
    var resultList = []
    var goodDetail = this.data.goodDetail

    var resultItem = {
      "goodId": goodDetail.goodId,
      "skuId": goodDetail.skuId,
      "buyCount": buyCount,
      "goodName": goodDetail.goodName,
      "nutrient": goodDetail.nutrient,
      "thumbUrl": goodDetail.thumbUrl,
      "basePrice": goodDetail.basePrice,
      "vipPrice": goodDetail.vipPrice,
      "expectSendTime": goodDetail.expectSendTime,
      "saleForm": goodDetail.saleForm,
    }
    resultList.push(resultItem)

    wx.navigateTo({
      url: '/pages/order/pre-order/pre-order?goodList=' + encodeURIComponent(JSON.stringify(resultList)),
    })
  },

  requestAddGoodToCard() {
    if (this.data.maxLimitBuyCount == 0) {
      uiUtil.showToast("抱歉,商品已售罄")
      return;
    }
    this.setData({
      confirmDialogType: 1
    })
    that.showConfirmDialog()
  },
  /**
   * 添加商品进购物车
   */
  requestAddGoodToCardConfirm() {
    if (this.data.maxLimitBuyCount == 0) {
      uiUtil.showToast("抱歉,商品已售罄")
      return;
    }

    var count = this.data.inputBuyCount
    if (!count || count <= 0) {
      uiUtil.showToast("请选择购买数量")
      return;
    }
    this.hideConfirmDialog()
    var goodDetail = this.data.goodDetail;
    httpUtil.PostRequest("add_good_to_card", {
      "goodId": goodDetail.goodId,
      "skuId": goodDetail.skuId,
      "buyCount": count
    }, {
      success(res) {
        that.ntfCartAddCount(goodDetail.goodId, goodDetail.skuId, count)
        uiUtil.showToast("添加购物车成功")
        app.cartSelectsAdd(goodDetail.goodId, goodDetail.skuId)
        if (res.cartCount) {
          that.setData({
            cartCount: res.cartCount
          })
          //更新全局变量
          app.resetCartCount(res.cartCount)
        }
      },
      fail(code, res) {
        uiUtil.showToast("添加购物车失败")
      },
      complete() {}
    })
  },

  /**
   * 通知上一页面，购物车商品数量发生变化
   */
  ntfCartAddCount(goodId, skuId, count) {
    try {
      var pages = getCurrentPages()
      var lastPage = pages[pages.length - 2]
      lastPage.onResultCartGoodCountAdd(goodId, skuId, count)
    } catch (e) {
      // console.log(e)
    }
  },


  onConfirmDialogInput(e) {
    var count = e.detail.value
    if (!count) {} else if (count > this.data.goodDetail.maxBuyCount) {
      uiUtil.showToast("已超出最大购买数量")
      count = this.data.goodDetail.maxBuyCount
    } else if (count > this.data.goodDetail.stockCount) {
      uiUtil.showToast("已超出库存数量")
      count = this.data.goodDetail.stockCount
    }

    this.setData({
      inputBuyCount: count
    })
  },

  //显示对话框
  showConfirmDialog: function() {
    that=this;
    that.setData({
      showConfirmDialog: true
    })
  },
  //隐藏对话框
  hideConfirmDialog: function() {
    that = this;
    that.setData({
      showConfirmDialog: false
    })
  },

  onConfirmDialogBtnClick() {
    if (this.data.confirmDialogType == 1) { //加入购物车
      that.requestAddGoodToCardConfirm()
    } else {
      that.onBuyClickConfirm()
    }
  },
  onConfirmDialogInputClick() {
    this.setData({
      dialogInputFocus: true,
    })
  }
})



function setChartOption(chart, xDatas, yValues) {

  var option = {
    grid: {
      top: '10%',
      bottom: '18%'
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xDatas,
      axisLabel: {
        color: '#969696'
      },
    },
    yAxis: {
      x: 'center',
      type: 'value',
      axisLabel: {
        color: '#C6C6C6'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: ['#D6D6D6']
        }
      },
      //   show: false
    },
    series: [{
      type: 'line',
      data: yValues,
      showSymbol: true,
      symbol: 'circle', //设定为实心点
      color: ["#CFB286"], //折现颜色
      areaStyle: {
        normal: {
          opacity: 0.3,
          color: new echarts.graphic.LinearGradient(
            0, 0, 0, 1, [{
                offset: 0,
                color: '#CFB286'
              },
              {
                offset: 0.3,
                color: '#CFB286'
              },
              {
                offset: 1,
                color: '#FFF'
              }
            ]
          )
        }
      },
    }]
  };

  chart.setOption(option);
}

